package client;

import entry.Member;
import java.awt.*;
import java.io.*;
import java.net.Socket;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;

public class ClientManager {

    private ClientManager(){}
    private static final ClientManager clientManager = new ClientManager();
    public static ClientManager getClientManager(){
        return clientManager;
    }

    private Socket socket;
    private String IP;
    private BufferedReader reader;
    private PrintWriter writer;
    private TextArea receiveArea;
    private Member member;

    public void connect(String IP, Member member){
        this.IP = IP;
        this.member = member;
        String memberJson = member.toString();
        new Thread(() -> {
            try {
                socket = new  Socket(IP, 8808);
                writer = new PrintWriter(
                        new OutputStreamWriter(
                                socket.getOutputStream(),"UTF-8"));
                reader = new BufferedReader(
                        new InputStreamReader(
                                socket.getInputStream(), "UTF-8"));

                String line;

                while ((line = reader.readLine()) != null) {
                    if (line.equals("Member")){
                        writer.println(memberJson);
                        writer.flush();
                        continue;
                    }
                    receiveArea.append(line + "\n");
                }
                writer.close();
                reader.close();
            } catch (UnknownHostException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }).start();
    }

    public void send(String out) {
        TimeZone zone = TimeZone.getTimeZone("GMT+8:00");
        SimpleDateFormat f = new SimpleDateFormat("yyyy年MM月dd日(E) HH:mm:ss");
        f.setTimeZone(zone);
        if(writer != null) {
            String msg = member.getUsername() + "(" + f.format(new Date()) + "):\n" + out + "\n";
            writer.write(msg);
            receiveArea.append(msg);
            writer.flush();
        }else {
            receiveArea.append("连接中断");
        }
    }

    public void setReceiveArea(TextArea receiveArea){
        this.receiveArea = receiveArea;
    }

    public void disconnect(){
        try {
            if (socket!=null){
                writer.println("disconnect");
                writer.flush();
                socket.close();
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
